package com.thinkgem.jeesite.modules.mobile.service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ckfinder.connector.utils.FileUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.ResponseResult;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentCommand;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentLog;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentNocheck;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentCommandService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentLogService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentNocheckService;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.messages.service.EleEquipmentMessagesService;
import com.thinkgem.jeesite.modules.publish.entity.EleSourceGroupPublish;
import com.thinkgem.jeesite.modules.publish.entity.EleTempletPublish;
import com.thinkgem.jeesite.modules.publish.service.EleSourceGroupPublishService;
import com.thinkgem.jeesite.modules.publish.service.EleTempletPublishService;
import com.thinkgem.jeesite.modules.source.entity.EleSource;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.entity.app.EleSourceApp;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.source.service.app.EleSourceAppService;
import com.thinkgem.jeesite.modules.sys.MessagesUtils;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.templet.entity.EleTemplet;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

/**
 * @author John
 * @Date 2017-06-07
 */
@Controller
@RequestMapping(value = "${adminPath}/fore")
public class EquiInterFaceService extends BaseController {
	@Autowired
	private EleEquipmentService eleEquipmentService;
    @Autowired
    private EleEquipmentNocheckService eleEquipmentNocheckService;
	@Autowired
	private EleEquipmentMessagesService messagesService;
	@Autowired
	private EleTempletService templetService;
	@Autowired
	private EleTempletPublishService templetPublishService;
	@Autowired
	private EleSourceGroupPublishService eleSourceGroupPublishService;
	@Autowired
	private EleSourceGroupService eleSourceGroupService;
	@Autowired
	private EleEquipmentCommandService eleEquipmentCommandService;
	@Autowired
	private EleEquipmentLogService eleEquipmentLogService;
    @Autowired
    private EleSourceAppService eleSourceAppService;

	@RequestMapping("state")
	@ResponseBody
	public ResponseResult state(String mac, Long time) {
		String forRequest = MessagesUtils.saveRequestMessages("state", mac, null, time);
		int result = eleEquipmentService.eleEquipmentIsOnLine(mac, new Date(time));
		ResponseResult responseResult;
		if (result > 0) {
			responseResult = new ResponseResult(mac);
		} else {
			responseResult = new ResponseResult(ResponseResult.FAILURE, mac);
		}
		MessagesUtils.saveResponseMessages("state", forRequest, responseResult);
		return responseResult;
	}

	/**
	 * 对设备进行设置
	 * 
	 * @param mac
	 * @param time
	 * @return
	 */
	@RequestMapping("config")
	@ResponseBody
	public ResponseResult config(String mac, Long time) {
		String forRequest = MessagesUtils.saveRequestMessages("config", mac, null, time);
		EleEquipment eleEquipment = eleEquipmentService.findEquipmentConfigByCode(mac);

		ResponseResult responseResult = new ResponseResult(ResponseResult.SUCCESS, mac, forRequest, eleEquipment);
		MessagesUtils.saveResponseMessages("config", forRequest, responseResult);
		return responseResult;
	}

	/**
	 * 对设备进行设置
	 * 
	 * @param mac
	 * @param time
	 * @return
	 */
	@RequestMapping("configResult")
	@ResponseBody
	public void configResult(String mac, Long time, String code, String cid) {
		MessagesUtils.saveRequestMessages("configResult", mac, null, time);
		messagesService.configResult(code, cid);
	}

    /**
     * 设备上报状态信息
     *
     * @param mac
     * @param time
     * @param data
     * @return
     */
	@RequestMapping("uploading")
	@ResponseBody
	public ResponseResult uploading(String mac, Long time, String data) {
		String forRequest = MessagesUtils.saveRequestMessages("uploading", mac, data, time);

        EleEquipment equipment = eleEquipmentService.findEquipmentConfigByCode(mac);
        int result;
        if(null == equipment){
            EleEquipmentNocheck eleEquipmentNocheck = JSONObject.parseObject(data, EleEquipmentNocheck.class);
            eleEquipmentNocheck.setCode(mac);
            eleEquipmentNocheckService.save(eleEquipmentNocheck);
            result = 1;
        }
        else{
            equipment = JSONObject.parseObject(data, EleEquipment.class);
            equipment.setCode(mac);
            result = eleEquipmentService.uploadingConfig(equipment);
        }

		ResponseResult responseResult;
		if (result > 0) {
			responseResult = new ResponseResult(mac);
		} else {
			responseResult = new ResponseResult(ResponseResult.FAILURE, mac);
		}
		MessagesUtils.saveResponseMessages("uploading", forRequest, responseResult);
		return responseResult;
	}

	/**
	 * 获取页面布局
	 *
	 * @param mac
	 * @param time
	 * @return
	 * @throws JAXBException
	 */
	@RequestMapping("theme")
	@ResponseBody
	public String theme(String mac, Long time) throws JAXBException {
		MessagesUtils.saveRequestMessages("theme", mac, null, time);
		EleTemplet templet = templetService.getbyTempleteByCode(mac);

		return templetPublishService.eleTempletToXml(templet);
	}

	/**
	 * 获取页面布局
	 *
	 * @param mac
	 * @param time
	 * @return
	 * @throws JAXBException
	 */
	@RequestMapping("publish")
	@ResponseBody
	public ResponseResult publish(String mac, Long time, HttpServletRequest request) throws JAXBException {
		MessagesUtils.saveRequestMessages("publish", mac, null, time);
		ResponseResult responseResult;
		EleEquipment eleEquipment = eleEquipmentService.findEquipmentConfigByCode(mac);
		List<EleSourceGroupPublish> publishList = eleSourceGroupPublishService.findListByEquipmentId(eleEquipment.getId(), EleSourceGroupPublish.DEL_FLAG_NORMAL);
		if(publishList.isEmpty()){
			responseResult = new ResponseResult(ResponseResult.FAILURE, mac);
		}
		else{
			EleSourceGroupPublish first = publishList.get(0);
			String groupId = first.getGroupId();
			EleSourceGroup esg = eleSourceGroupService.get(groupId);

			List<EleSource> esList = esg.getEleSourceList();
			if(null == esList || esList.isEmpty()){
				responseResult = new ResponseResult(ResponseResult.FAILURE, mac);
			}
			else{
                EleSource eleSource = esList.get(0);
                String type = eleSource.getType();

                String basePath = DictUtils.getDictValue("basePath", "systemvalue", "");

                JSONObject data = new JSONObject();
                if(1 == esList.size() && "apk".equals(type)){
                    String sourceItemId = eleSource.getContent();
                    EleSourceApp sourceApp= eleSourceAppService.get(sourceItemId);
                    data.put("type", type);
                    data.put("url", basePath+sourceApp.getPath());
                }
                else{
                    boolean isPackage = false;
                    for(EleSource es : esList){
                        if(!type.equals(es.getType())){
                            isPackage = true;
                        }
                    }

                    data.put("type", isPackage ? "interface" : type);

                    String zipPath = basePath + "/theme/" + groupId + "/" + groupId + ".zip";

                    data.put("url", zipPath);

                }
                String cid = first.getPublishBatch();
                responseResult = new ResponseResult(ResponseResult.SUCCESS, mac, cid, data);
            }
		}
		return responseResult;
	}

	/**
	 * 对设备进行设置
	 *
	 * @param mac
	 * @param time
	 * @return
	 */
	@RequestMapping("publishResult")
	@ResponseBody
	public void publishResult(String mac, Long time, String code, String cid) {
		MessagesUtils.saveRequestMessages("publishResult", mac, null, time);
		messagesService.configResult(code, cid);
	}
	@RequestMapping(value="interface")
	@ResponseBody
	public ResponseResult equipmentInferface(HttpServletRequest request){
		String mac = request.getParameter("mac");
		Long time = Long.parseLong(request.getParameter("time"));
		String data = request.getParameter("data");
		String code = request.getParameter("code");
		String cid = request.getParameter("cid");
		String filename = request.getParameter("filename");
		String filetype = request.getParameter("filetype");
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		ResponseResult responseResult = null; 
		if(StringUtils.isEmpty(cid)){
			responseResult = processRequest(mac, time, data);
		}else{
			MultipartFile file = null;
			if(isMultipart){
				MultipartHttpServletRequest mmr = (MultipartHttpServletRequest) request;
				file = mmr.getFile("file");   
			}
			responseResult = processReponse(mac, time, code, cid, file, filename, filetype);
		}
		return responseResult;
	}
	private ResponseResult processReponse(String mac, Long time,String code,String cid,MultipartFile file,String filename,String filetype){
		long currentTime = System.currentTimeMillis();
		ResponseResult responseResult = null;
		MessagesUtils.saveRequestMessages("interfaceResult", mac, null, time);
			EleEquipment eleEquipment = eleEquipmentService.get(cid);
			EleSourceGroupPublish group = eleSourceGroupPublishService.get(cid);
			EleTempletPublish  templet = templetPublishService.get(cid);
			EleEquipmentCommand command = eleEquipmentCommandService.get(cid);
			if(eleEquipment != null){
				logger.info("Equipment");
				eleEquipmentService.updateOnlineStatus(eleEquipment.getId(), "1");

				eleEquipmentService.updatePublishStatus(eleEquipment.getId(), "0");
			}else if(group != null){
				logger.info("SourceGroup");

				eleSourceGroupPublishService.updatePublishStatus(group.getId(), "0");
			}else if(templet != null){
				logger.info("Template");

				templetPublishService.updatePublishStatus(templet.getId(), "0");
			}
				else if(command != null){
				logger.info("Command");
				String dirPath = Global.getUserfilesBaseDir()+"upload/" + command.getType() + "/";
				String fullPath = Global.getUserfilesBaseDir()+"upload/" + command.getType() + "/" + filename;
				String filePath = "upload/" + command.getType() + "/" + filename;
				if(file != null){
					// 转存文件
				try {
					File dir = new File(dirPath);
					if(!dir.exists()  && dir.isDirectory()){
						dir.mkdirs();
					}
					File tmp = new File(fullPath);
					if(tmp.exists()){
						FileUtils.delete(tmp);
					}
					File log = new File(fullPath);
					file.transferTo(log);
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				EleEquipment tmp = eleEquipmentService.findEquipmentByCode(mac);
				EleEquipmentLog log = eleEquipmentLogService.findLogByPath(filePath);
				if(log == null){
					log = new EleEquipmentLog();
					log.setEquipmentId(command.getEquipmentId());
					log.setType(filetype);
					log.setPath(filePath);
					log.setName(filename);
					eleEquipmentLogService.save(log);
				}else{
					log.setEquipmentId(tmp.getId());
					log.setUpdateDate(new Date(System.currentTimeMillis()));
					eleEquipmentLogService.save(log);
					//command.setEquipmentId(tmp.getId());
					//eleEquipmentCommandService.save(command);
				}
				}
				eleEquipmentCommandService.delete(command);
			}
		
		responseResult = new ResponseResult();
		responseResult.setMethod("response");
		responseResult.setTime(currentTime);
		responseResult.setMac(mac);
		responseResult.setCode(ResponseResult.SUCCESS);
		return responseResult;
	}
	private ResponseResult processRequest(String mac,Long time,String data){
		MessagesUtils.saveRequestMessages("request", mac, data, time);
		ResponseResult responseResult = null;
		long currentTime = System.currentTimeMillis();
		//保持连接状态
		int result = eleEquipmentService.eleEquipmentIsOnLine(mac, new Date(time));
		if (result > 0) {
			logger.info("设备状态更新成功");
		}
		EleEquipment eleEquipment = eleEquipmentService.findEquipmentConfigByCode(mac);
		//未审核接入设备
		if(eleEquipment == null){
			EleEquipmentNocheck newEleEquipment = new EleEquipmentNocheck();
			newEleEquipment.setCode(mac);

			List<EleEquipmentNocheck> checkList = eleEquipmentNocheckService.findList(newEleEquipment);
			if(checkList.isEmpty()){
			newEleEquipment.setFullscreen(1);
			newEleEquipment.setTitledisplay(1);
			newEleEquipment.setTimedisplay(1);
			newEleEquipment.setSubtitledisplay(1);
			//newEleEquipment.setResolution("'1'");

			newEleEquipment.setUpdateDate(new Date(time));
			newEleEquipment.setDelFlag(EleEquipment.DEL_FLAG_NORMAL);
			eleEquipmentNocheckService.save(newEleEquipment);
			}
			
//			responseResult = new ResponseResult();
//			responseResult.setMethod("response");
//			responseResult.setTime(currentTime);
//			responseResult.setMac(mac);
//			responseResult.setCode(ResponseResult.SUCCESS);
			return null;
		}
		List<EleEquipment> eleList = new ArrayList<EleEquipment>();
		eleList.add(eleEquipment);
		List<EleEquipmentCommand> commandList = eleEquipmentCommandService.findListByEquipments(eleList, EleEquipmentCommand.DEL_FLAG_NORMAL);
		if(commandList.size() > 0){
			EleEquipmentCommand eec = commandList.get(0);
			JSONObject ret = new JSONObject();
			ret.put("type", eec.getType());
			responseResult = new ResponseResult();
			responseResult.setMethod("response");
			responseResult.setTime(currentTime);
			responseResult.setMac(mac);
			responseResult.setCode(ResponseResult.SUCCESS);
			responseResult.setData(ret);
			responseResult.setCid(eec.getId());
			
			return responseResult;
		}
		//处理设备上报信息
		if(data != null){
			EleEquipment equipment = eleEquipmentService.findEquipmentConfigByCode(mac);
			int updateResult;
			if (null == equipment) {
				EleEquipmentNocheck eleEquipmentNocheck = JSONObject.parseObject(data, EleEquipmentNocheck.class);
				eleEquipmentNocheck.setCode(mac);
				eleEquipmentNocheckService.save(eleEquipmentNocheck);
				updateResult = 1;
			} else {
				System.out.println(data);
				equipment = JSONObject.parseObject(data, EleEquipment.class);
				JSONObject json = JSONObject.parseObject(data);
				if(equipment.getOrientation().equals("0") || equipment.getOrientation().equals("2")){
					equipment.setOrientation("0");
				}else{
					equipment.setOrientation("1");
				}
				equipment.setResolution(json.getString("resolution"));
				equipment.setCode(mac);
				updateResult = eleEquipmentService.uploadingConfig(equipment);
			}
			responseResult = new ResponseResult();
			if (updateResult <= 0) {
				responseResult = new ResponseResult(ResponseResult.FAILURE, mac);
			} else {
				responseResult = new ResponseResult();
				responseResult.setMethod("response");
				responseResult.setTime(currentTime);
				responseResult.setMac(mac);
				responseResult.setCode(ResponseResult.SUCCESS);
			}			
			return responseResult;
		}
		
		List<EleSourceGroupPublish> publishList = eleSourceGroupPublishService
				.findListByEquipmentId(eleEquipment.getId(), EleSourceGroupPublish.DEL_FLAG_NORMAL);
		List<EleTempletPublish> templetList = templetPublishService.findListByEquipmentId(eleEquipment.getId(), EleSourceGroupPublish.DEL_FLAG_NORMAL);
		long equipmentPublishTime = currentTime;
		long groupPublishTime = currentTime;
		long templatePublishTime = currentTime;
		
		if(eleEquipment != null && eleEquipment.getIsPublish().equals("2")){
			equipmentPublishTime = eleEquipment.getUpdateDate().getTime();
		}
		if(!publishList.isEmpty()){
			groupPublishTime = publishList.get(0).getUpdateDate().getTime();
		}
		if(!templetList.isEmpty()){
			templatePublishTime = templetList.get(0).getUpdateDate().getTime();
		}
		long tmpMin = Math.min(equipmentPublishTime, groupPublishTime);
		long min = Math.min(tmpMin, templatePublishTime);
		
		//无更新
		if(min == currentTime){
			responseResult = new ResponseResult();
			responseResult.setCode(ResponseResult.SUCCESS);
			responseResult.setMac(mac);
			responseResult.setTime(min);
			responseResult.setMethod("response");
			return responseResult;
		}
		
		//对设备进行配置 
		if(min == equipmentPublishTime){
			responseResult = new ResponseResult();
			responseResult.setCode(ResponseResult.SUCCESS);
			responseResult.setMac(mac);
			responseResult.setMethod("config");
			responseResult.setTime(min);
			responseResult.setData(eleEquipment);
			responseResult.setCid(eleEquipment.getId());
			eleEquipmentService.updateOnlineStatus(eleEquipment.getId(), "2");
			return responseResult;


		}else
			//发布新的资源包
			if(min == groupPublishTime){
			EleSourceGroupPublish first = publishList.get(0);
			String groupId = first.getGroupId();
			EleSourceGroup esg = eleSourceGroupService.get(groupId);
		    String basePath = DictUtils.getDictValue("basePath", "systemvalue", Global.getUserfilesBaseDir());
		    //String localPath = Global.getUserfilesBaseDir()+"theme/source/" + groupId + "/" + groupId + ".zip";
		    String zipPath = basePath + "/theme/source/" + groupId + "/" + groupId + ".zip";
			JSONObject ret = new JSONObject();
			
			List<EleSource> esList = esg.getEleSourceList();
			System.out.println(esg.getEleSourceList().size());
			if(null == esList || esList.isEmpty()){
				eleSourceGroupPublishService.updatePublishStatus(first.getId(), "0");
				responseResult = new ResponseResult(ResponseResult.FAILURE, mac);			
				return responseResult;
			}
			else{
				String type = esList.get(0).getType();
				boolean isPackage = false;
				for(EleSource es : esList){
					if(!type.equals(es.getType())){
						isPackage = true;
					}
				}	
				ret.put("type", isPackage ? "interface" : type);
				ret.put("url", zipPath);
			}
			responseResult = new ResponseResult();
			responseResult.setCode(ResponseResult.SUCCESS);
			responseResult.setMac(mac);
			responseResult.setMethod("publish");
			responseResult.setTime(min);
			responseResult.setData(ret);
			responseResult.setCid(first.getId());
			return responseResult;
		}else 
			//发布新的界面包
			if(min == templatePublishTime){
				JSONObject ret = new JSONObject();
				ret.put("type", "interface");

			EleTempletPublish first = templetList.get(0);
			EleTemplet templet = templetService.get(first.getTemplet().getId());
			String templateId = templet.getId();
		    String basePath = DictUtils.getDictValue("basePath", "systemvalue", Global.getUserfilesBaseDir());
			//String localPath = Global.getUserfilesBaseDir()+"theme/source/"+templateId+"/"+templateId+".zip";
		    String zipPath = basePath + "/theme/source/"+templateId+"/"+templateId+".zip";

		   // File tmpfile = new File(localPath);
			//if(tmpfile.exists()){
				ret.put("url", zipPath);
			//}
			responseResult = new ResponseResult();
			responseResult.setCode(ResponseResult.SUCCESS);
			responseResult.setMac(mac);
			responseResult.setMethod("publish");
			responseResult.setTime(min);
			responseResult.setData(ret);
			responseResult.setCid(first.getId());
			return responseResult;
		}
		return responseResult;
	}

}
